import 'package:color_dart/color_dart.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/style.dart';
import 'package:im_flutter_sdk_example/components/labels/index.dart';
import 'package:im_flutter_sdk_example/jsonserialize/recommend/news.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:im_flutter_sdk_example/jsonserialize/recommend/newsDetail.dart';
import 'package:im_flutter_sdk_example/pages/expert/widgets/main_title.dart';
import 'package:im_flutter_sdk_example/pages/news/comment.dart';
import 'package:im_flutter_sdk_example/pages/photoview/fade_route.dart';
import 'package:im_flutter_sdk_example/pages/photoview/index.dart';
import 'package:im_flutter_sdk_example/provider/comment_model.dart';
import 'package:im_flutter_sdk_example/utils/global.dart';
import 'package:im_flutter_sdk_example/utils/time_util.dart';
import 'package:im_flutter_sdk_example/utils/screen.dart';
import 'package:provider/provider.dart';
import 'package:quiver/strings.dart';
import 'package:keyboard_visibility/keyboard_visibility.dart';

class NewsDetail extends StatefulWidget {
  @override
  _NewsDetailState createState() => _NewsDetailState();
}

class _NewsDetailState extends State<NewsDetail> {
  // 当前键盘是否是激活状态
  bool isKeyboardActived = false;
  KeyboardVisibilityNotification _keyboardVisibility =
      new KeyboardVisibilityNotification();
  TextEditingController _textController = TextEditingController();
  FocusNode _focusNode = FocusNode();

  int _keyboardVisibilitySubscriberId;
  NewsDetailsData newsDetails;
  bool isLike = false; //新闻是否点赞
  bool isCollect = false; //新闻是否收藏
  @override
  void initState() {
    super.initState();
    Future.delayed(Duration.zero, () {
      _registeKeyboardListener();
      final NewsData item =
          ModalRoute.of(context).settings.arguments; //路由获取新闻内容
      CommentModelProvider _formData =
          Provider.of<CommentModelProvider>(context);
      _formData.resetPlaceHolder();
      //获取新闻详情
      getDetail(item.id);
      newsIsCollect(item.id);
    });
  }

  //新闻是否收藏
  void newsIsCollect(String id) async {
    var result = await G.req.news.reqNewsIsCollect(objType: 0, objId: id);
    if (result.data['status'] == 1) {
      isCollect = result.data['data'];
      this.setState(() {});
    }
  }

  _registeKeyboardListener() {
    isKeyboardActived = _keyboardVisibility.isKeyboardVisible;
    _keyboardVisibilitySubscriberId = _keyboardVisibility.addNewListener(
      onChange: (bool visible) {
        if (visible == false) {
          // clear text
          CommentModelProvider _formData =
              Provider.of<CommentModelProvider>(context);
          _formData.resetPlaceHolder(); //重置占位符
          print('xxx');
        }
        setState(() {
          isKeyboardActived = visible;
        });
      },
    );
  }

  String _bestMatchCompany(String org) {
    // return org;
    List<String> companyNames = org.split(',');
    if (companyNames.length != 0) {
      return companyNames[1];
    }
    return "";
  }

  // 相关企业
  List<Widget> _buildRelativeCompany() {
    return [
      isBlank(newsDetails.org) ? G.emptyBox() : MainTitle(title: '相关企业/单位'),
      GestureDetector(
        onTap: () => {
          G.pushNamed('/company_info', arguments: {"item": newsDetails})
        },
        child: isBlank(newsDetails.org)
            ? G.emptyBox()
            : Container(
                padding: EdgeInsets.only(top: 10, bottom: 20),
                child:
                    Row(mainAxisAlignment: MainAxisAlignment.start, children: [
                  Expanded(child: Text(newsDetails.org ?? '未知来源')),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text('查看详情',
                        maxLines: 20,
                        style: TextStyle(
                            color: rgba(72, 107, 157, 1), fontSize: 14)),
                  )
                ])),
      )
    ];
  }

  // 相关成果
  List<Widget> _buildRelativeProject() {
    return [
      isBlank(newsDetails.org) ? G.emptyBox() : MainTitle(title: '相关成果'),
    ];
  }

  // 相关专家
  List<Widget> _buildRelativeExpert() {
    return [
      isBlank(newsDetails.org) ? G.emptyBox() : MainTitle(title: '相关专家'),
    ];
  }

  @override
  Widget build(BuildContext context) {
    CommentModelProvider commentProvider =
        Provider.of<CommentModelProvider>(context);
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.white,
          elevation: 0,
          leading: Builder(builder: (BuildContext context) {
            return IconButton(
                icon: new Icon(Icons.arrow_back, color: Colors.black),
                onPressed: () {
                  Navigator.pop(context, true);
                });
          }),
        ),
        body: SafeArea(
          child: newsDetails != null
              ? Column(
                  children: [
                    Expanded(
                      child: InkWell(
                        onTap: () {
                          resetComment();
                        },
                        child: Container(
                          padding: EdgeInsets.fromLTRB(16, 0, 16, 0),
                          color: Colors.white,
                          child: SingleChildScrollView(
                            child: Column(
                              children: [
                                Text(
                                  "${newsDetails.title}",
                                  style: TextStyle(
                                      color: rgba(51, 51, 51, 1),
                                      fontSize: 42.nsp,
                                      fontWeight: FontWeight.bold),
                                ),
                                Row(children: [
                                  Text("来源:",
                                      style: TextStyle(
                                          color: rgba(163, 163, 163, 1),
                                          fontSize: 24.nsp)),
                                  Padding(
                                    padding: const EdgeInsets.symmetric(
                                        horizontal: 8, vertical: 16),
                                    child: Text(
                                      '${newsDetails.source ?? "其他"}',
                                      style: TextStyle(
                                          color: rgba(163, 163, 163, 1),
                                          fontSize: 24.nsp),
                                    ),
                                  ),
                                ]),
                                Padding(
                                  padding: EdgeInsets.symmetric(vertical: 20),
                                  child: Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      _buildWords(newsDetails),
                                      Text(
                                          '${TimeUtil.getFormatTime(newsDetails.date)}',
                                          style: TextStyle(
                                              color: rgba(163, 163, 163, 1),
                                              fontSize: 24.nsp))
                                    ],
                                  ),
                                ),
                                Divider(
                                    height: 2, color: rgba(235, 235, 235, 1)),
                                Html(
                                  data: newsDetails.bodyHtml,
                                  style: {
                                    "div": Style(
                                        fontSize: FontSize(34.nsp),
                                        color: rgba(68, 68, 68, 1))
                                  },
                                  onLinkTap: (url) {
                                    G.pushNamed('/news_web', arguments: url);
                                  },
                                  onImageTap: (src) {
                                    print(src);
                                    Navigator.of(context).push(new FadeRoute(
                                        page: PhotoViewGalleryScreen(
                                      images: [src], //传入图片list
                                      index: 0, //传入当前点击的图片的index
                                    )));
                                  },
                                  onImageError: (exception, stackTrace) {
                                    print(exception);
                                  },
                                ),
                                Divider(
                                  thickness: 2,
                                  color: rgba(249, 249, 249, 1),
                                ),
                                Comment(
                                    id: newsDetails.id,
                                    type: 0,
                                    getFocus: getFocus),
                                ..._buildRelativeCompany(),
                                ..._buildRelativeProject(),
                                ..._buildRelativeExpert()
                              ],
                            ),
                          ),
                        ),
                      ),
                    ),
                    Container(
                        width: double.infinity,
                        padding: EdgeInsets.only(
                            top: 8, bottom: 14, left: 16, right: 16),
                        decoration: BoxDecoration(
                            color: Colors.white,
                            boxShadow: [
                              BoxShadow(
                                  color: Colors.white10, offset: Offset(0, 10)),
                            ],
                            border: Border(
                                top: BorderSide(
                                    width: 1, color: rgba(235, 235, 235, 1)))),
                        child: Container(
                          // padding: EdgeInsets.only(bottom: 30),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Container(
                                  decoration: BoxDecoration(
                                    borderRadius:
                                        BorderRadius.all(Radius.circular(3)),
                                  ),
                                  constraints: BoxConstraints(
                                      minWidth: 160,
                                      minHeight: 36,
                                      maxWidth: 160,
                                      maxHeight: 108),
                                  child: TextField(
                                    controller: _textController,
                                    focusNode: _focusNode,
                                    maxLines: null,
                                    keyboardType: TextInputType.multiline,
                                    textInputAction: TextInputAction.send,
                                    onSubmitted: _postComment,
                                    decoration: InputDecoration(
                                      fillColor: rgba(249, 249, 249, 1),
                                      filled: true,
                                      contentPadding: EdgeInsets.only(left: 12),
                                      enabledBorder: OutlineInputBorder(
                                          borderSide: BorderSide(
                                              color: rgba(249, 249, 249, 1)),
                                          borderRadius: BorderRadius.all(
                                              Radius.circular(3))),
                                      hintText:
                                          '${commentProvider.commentPlaceHolderText}',
                                      hintStyle: TextStyle(
                                          color: Colors.grey, fontSize: 14),
                                      focusedBorder: OutlineInputBorder(
                                          borderSide: BorderSide(
                                              color: rgba(249, 249, 249, 1)),
                                          borderRadius: BorderRadius.all(
                                              Radius.circular(3))),
                                    ),
                                  )),
                              Expanded(
                                child: Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceAround,
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    isCollect
                                        ? InkWell(
                                            onTap: () {
                                              cancelCollect(newsDetails.id);
                                            },
                                            child: Image.asset(
                                                'lib/assets/images/footer_star_active.png',
                                                width: 22,
                                                height: 22),
                                          )
                                        : InkWell(
                                            onTap: () {
                                              addCollect(newsDetails.id);
                                            },
                                            child: Image.asset(
                                                'lib/assets/images/footer_star.png',
                                                width: 22,
                                                height: 22),
                                          ),
                                    isLike
                                        ? InkWell(
                                            onTap: () {
                                              cancelLike(newsDetails.id);
                                            },
                                            child: Image.asset(
                                                'lib/assets/images/footer_zan_active.png',
                                                width: 22,
                                                height: 22),
                                          )
                                        : InkWell(
                                            onTap: () {
                                              addLike(newsDetails.id);
                                            },
                                            child: Image.asset(
                                                'lib/assets/images/footer_zan.png',
                                                width: 22,
                                                height: 22),
                                          ),
                                    Image.asset(
                                        'lib/assets/images/footer_share.png',
                                        width: 22,
                                        height: 22),
                                    InkWell(
                                      onTap: () {
                                        _postComment('v');
                                      },
                                      child: Image.asset(
                                          'lib/assets/images/footer_send.png',
                                          width: 22,
                                          height: 22),
                                    ),
                                  ],
                                ),
                              )
                            ],
                          ),
                        )),
                  ],
                )
              : Column(
                  children: [],
                ),
        ));
  }

  _buildWords(NewsDetailsData newsDetails) {
    List<String> words = newsDetails.kwdWord;

    if (newsDetails.kwdWord.length > 3) {
      words = newsDetails.kwdWord.sublist(0, 3);
    }
    return Wrap(
      spacing: 2,
      runSpacing: 5,
      direction: Axis.horizontal,
      children: words.map((e) => LabelKwdNews(name: "#$e")).toList(),
    );
  }

  void _postComment(v) {
    var content = _textController.text;
    CommentModelProvider _formData = Provider.of<CommentModelProvider>(context);
    if (content == '') {
      G.toast('请输入评论内容');
      return;
    }
    //发表评论
    if (_formData.isReplay == false) {
      _formData.postComment(content, 0, newsDetails.id, clearTextFild);
    }
    //回复评论
    if (_formData.isReplay == true) {
      _formData.replayComment(content, 0, newsDetails.id, clearTextFild);
    }
    loseFocus();
  }

  //输入框获取焦点
  void getFocus() {
    FocusScope.of(context).requestFocus(_focusNode);
  }

  //输入框失去焦点
  void loseFocus() {
    FocusScope.of(context).unfocus();
  }

  //清空输入框
  void clearTextFild() {
    _textController.text = '';
  }

  @override
  void dispose() {
    super.dispose();
    _keyboardVisibility.removeListener(_keyboardVisibilitySubscriberId);
  }

  //新闻点赞
  void addLike(String id) async {
    var result = await G.req.news.addNewsLikes(newsId: id);
    print('点赞结果$result');
    if (result.data['status'] == 1) {
      isLike = true;
      this.setState(() {});
    }
  }

  //新闻取消点赞
  void cancelLike(String id) async {
    var result = await G.req.news.cancelNewsLikes(newsId: id);
    print('取消点赞结果$result');
    if (result.data['status'] == 1) {
      isLike = false;
      this.setState(() {});
    }
  }

  //新闻收藏
  void addCollect(String id) async {
    var result = await G.req.news.addNewsCollect(objId: id, objType: 0);
    print('收藏结果$result');
    if (result.data['status'] == 1) {
      G.toast('收藏成功');
      newsIsCollect(id);
    }
  }

  //新闻取消收藏
  void cancelCollect(String id) async {
    print('$id');
    var result = await G.req.news.cancelNewsCollect(objId: id, objType: 0);
    print('收藏结果$result');
    if (result.data['status'] == 1) {
      G.toast('取消收藏');
      newsIsCollect(id);
    }
  }

  //加载新闻详情
  void getDetail(String id) async {
    print(id);
    var result = await G.req.news.reqNewsDetails(id: id);
    newsDetails = NewsDetailsData.fromJson(result.data['data']);
    var userData = G.user.data;
    print('新闻详情${newsDetails.usersLike.contains(userData.userId.toString())}');
    isLike = newsDetails.usersLike.contains(userData.userId.toString());
    this.setState(() {});
  }

  //重置评论
  void resetComment() {
    print(isKeyboardActived);
    if (isKeyboardActived) {
      clearTextFild();
      loseFocus();
      CommentModelProvider _formData =
          Provider.of<CommentModelProvider>(context);
      _formData.resetPlaceHolder();
    }
  }
}
